﻿using System.Security.Cryptography;
using System.Text;
using MongoDB.Bson;
using MongoDB.Driver;
using WebApplication1.Models;
using Microsoft.AspNetCore.SignalR;

namespace WebApplication1.Repository;

public class UserRepository
{
    private readonly IMongoCollection<User> _collection;

    public UserRepository(IMongoDatabase database)
    {
        _collection = database.GetCollection<User>("Users");
    }

    // 添加新用户
    public async Task CreateUserAsync(User user)
    {
        await _collection.InsertOneAsync(user);
    }

    // 根据用户名查找用户
    public async Task<User?> GetByUsernameAsync(string username)
    {
        return await _collection.Find(u => u.UserName == username).FirstOrDefaultAsync();
    }

    // 根据 ObjectId 查找用户
    public async Task<User?> GetByIdAsync(string id)
    {
        var objectId = ObjectId.Parse(id);
        return await _collection.Find(u => u.Id == objectId).FirstOrDefaultAsync();
    }

    // 登录验证（示例：明文密码，建议加密）
    public async Task<User?> ValidateUserAsync(string username, string password)
    {
        return await _collection.Find(u => u.UserName == username && u.Password == password).FirstOrDefaultAsync();
    }

    // 可选：获取所有用户（不推荐暴露全部）
    public async Task<List<User>> GetAllUsersAsync()
    {
        return await _collection.Find(_ => true).ToListAsync();
    }
    
    public async Task<bool> ValidateUserPasswordAsync(string username, string password)
    {
        var user = await _collection.Find(u => u.UserName == username).FirstOrDefaultAsync();
        if (user == null)
        {
            return false;
        }

        // 使用加密后的密码进行比较
        using var sha256 = SHA256.Create();
        var hashedPassword = Convert.ToBase64String(sha256.ComputeHash(Encoding.UTF8.GetBytes(password)));
        return user.Password == hashedPassword;
    }
}